/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-12-16 15:40:23
 * @filename : controller/manual_renew.js
 * @version : 
 * @description : 
 */

define(function(require, exports, module){
    var name = 'Manual Renew', mId = 'manual_renew',   
        highchartMC = require('{model}highchart'), 
        highcharts = require('highcharts'),
        tpl = require('{view}page_gold.tpl'),
        tplH = require('{view}head_gold.tpl'),
        tplT = require('{view}table.tpl'),
        tplS = require('{view}select.tpl');

    var highchartM = new highchartMC.highchartM;

    var tempOpt = {
             engine : '',
             begin_date : null,
             end_date : null,
             group : 'day'
        };
 
    var ManualRenewView = Backbone.View.extend({

        initialize: function (obj) { 
            this.run(obj);
        },

        run : function(obj) {
            if ($('.main').length !== 3) { 
                Backbone.routerObj.navigate('index/w/'+mId, { trigger: true });return;
            } else {
                this.tplRender();
            }
        },

        tplRender : function() {
            if ($('#'+mId).length < 1) { 
                $('#index_right').append(_.template(tpl)({obj:{name:name,mId:mId}}));
                $('#'+mId).find('.m_head').append(_.template(tplH));
                this.defaultOpt();
                this.afterBindEvt();
                this.fetchData(tempOpt); 
            } else {
                $('#'+mId).css('display','block');
            } 
        },

        afterBindEvt : function() {
            var tthis = this,dom = $('#'+mId);

            new Pikaday({
                field: dom.find('.from_time')[0],
                firstDay: 1,
                minDate: new Date('1997-01-01'),
                maxDate: new Date('2020-12-31'),
                yearRange: [1997,2020]
            });

            new Pikaday({
                field: dom.find('.to_time')[0],
                firstDay: 1,
                minDate: new Date('1997-01-01'),
                maxDate: new Date('2020-12-31'),
                yearRange: [1997,2020]
            });

            dom.find('.selectTime').on('change',function(){
                var val = $(this).val();
                share.setInputDate(val,mId);
            });


            dom.find('.do').on('click',function(){
                var bool = share.getPostData(tempOpt,mId); 
                if (bool) { 
                    tthis.fetchData(tempOpt);
                }
            });

        },

        defaultOpt : function() {
            var dom = $('#'+mId);
            this.selectSite();
            share.setInputDate('last-week',mId);
            tempOpt.end_date = dom.find('.to_time').val();
            tempOpt.begin_date = dom.find('.from_time').val(); 
            tempOpt.group  = 'day';
            tempOpt.engine  = '';
            
            dom.find('.selectGroup').find('option').not(":first").remove(); 
        },

        selectSite : function() {
             var siteInfo =  share.getAllSites(1);
             $('#'+mId).find('.selectInfo').html(_.template(tplS)({obj:siteInfo}));
        }, 

        fetchData : function(data) {
            var tthis = this,
                ajaxOpt = {
                url : seajs.data.vars.apiUrl+'total_gold',
                type : 'POST',
                data : data,
                success : function(data) {
                    tthis.fetchSuccess(data);
                },
                error : function(xhr, errorType, error) {
                },
                complete : function(xhr,status){
                    share.load($('#'+mId),false); 
                }
            };
           
            share.load($('#'+mId),true); 
            share.ajax(ajaxOpt,true);
        },

        fetchSuccess : function(data) {
            //console.log(data);
            _.each(data,function(obj) {
                if (parseInt(Number(obj.LAST_W_EXPIRED_MEMBERS)) >0) {
                    obj.WEEK_RATIO =(parseInt(obj.LAST_W_EXPIRED_MEMBERS_RE_P) * 100 / parseInt(obj.LAST_W_EXPIRED_MEMBERS)).toFixed(2);
                } else {
                    obj.WEEK_RATIO = 0;
                }

                if (parseInt(Number(obj.LAST_M_EXPIRED_MEMBERS)) >0) {
                    obj.MONTH_RATIO =(parseInt(obj.LAST_M_EXPIRED_MEMBERS_RE_P) * 100 / parseInt(obj.LAST_M_EXPIRED_MEMBERS)).toFixed(2);
                } else {
                    obj.MONTH_RATIO = 0;
                }

                if (parseInt(Number(obj.LAST_3M_EXPIRED_MEMBERS)) >0) {
                    obj.QUARTER_RATIO =(parseInt(obj.LAST_3M_EXPIRED_MEMBERS_RE_P) * 100 / parseInt(obj.LAST_3M_EXPIRED_MEMBERS)).toFixed(2);
                } else {
                    obj.QUARTER_RATIO = 0;
                }
                //console.log(obj.QUARTER_RATIO);
            });
            this.details(data);
            this.changeHighChartM(data);  
        },

        details : function(data) {
            var arr = [];
                arr.push({name:'Date',val:'FMT_DATE',title:'Date'});
                arr.push({name:'Expired in week',val:'LAST_W_EXPIRED_MEMBERS',title:'Total number of expired gold.'});
                arr.push({name:'Renewed in week',val:'LAST_W_EXPIRED_MEMBERS_RE_P',title:'Repaid number in expired gold'});
                arr.push({name:'Ratio in week',val:'WEEK_RATIO',unit:'%',title:'Renewed / Expired'});
                arr.push({name:'',val:''});
                arr.push({name:'Expired in month',val:'LAST_M_EXPIRED_MEMBERS',title:'Total number of expired gold'});
                arr.push({name:'Renewed in month',val:'LAST_M_EXPIRED_MEMBERS_RE_P',title:'Repaid number in expired gold'});
                arr.push({name:'Ratio in month',val:'MONTH_RATIO',unit:'%',title:'Renewed / Expired'});
                arr.push({name:'',val:''});
                arr.push({name:'Expired in quarter',val:'LAST_3M_EXPIRED_MEMBERS',title:'Total number of expired gold'});
                arr.push({name:'Renewed in quarter',val:'LAST_3M_EXPIRED_MEMBERS_RE_P',title:'Repaid number in expired gold'});
                arr.push({name:'Ratio in quarter',val:'QUARTER_RATIO',unit:'%',title:'Renewed / Expired'});

            data = _.clone(data).reverse();
            $('#'+mId).find('.table').html(_.template(tplT)({obj:data,arr:arr}));
        },

        changeHighChartM : function(arr) {
            var xAxis = highchartM.get('xAxis'),
                yAxis = highchartM.get('yAxis'),
                tooltip = highchartM.get('tooltip');
                series = highchartM.get('series'),
                chart = highchartM.get('chart'),
                title = highchartM.get('title'),
                plotOptions = highchartM.get('plotOptions');

                plotOptions = {};
                title = {text : 'Manual Renew'};
                chart = {type : 'line',width:$('#index_right').width()}; 
                xAxis = {categories : _.pluck(arr,'DATE')}; 
                yAxis = {
                    title: {
                        text: 'rate(%)',
                        style: {
                            color: '#ff0000'
                        }

                    },
                    labels: {
                        format: '{value} %',
                        style: {
                            color: '#FF0000'
                        }
                    }
                };
                
                tooltip = {shared: true};

                series =  [{
                    name: 'week-ratio',
                    data: _.map(_.pluck(arr,'WEEK_RATIO'),function(num){return Number(num)}),
                    dataLabels: {
                        enabled: arr.length < share.dataLabelNum ? true : false
                    }
                },{
                    name: 'month-ratio',
                    data: _.map(_.pluck(arr,'MONTH_RATIO'),function(num){return Number(num)}),
                    dataLabels: {
                        enabled: arr.length < share.dataLabelNum ? true : false
                    }
                },{
                    name: 'quarter-ratio',
                    data: _.map(_.pluck(arr,'QUARTER_RATIO'),function(num){return Number(num)}),
                    dataLabels: {
                        enabled: arr.length < share.dataLabelNum ? true : false
                    }
                }];

                highchartM.set('tooltip',tooltip);
                highchartM.set('plotOptions',plotOptions); 
                highchartM.set('title',title); 
                highchartM.set('xAxis',xAxis); 
                highchartM.set('yAxis',yAxis); 
                highchartM.set('series',series);
                highchartM.set('chart',chart);
                this.renderHighChart();     
        }, 

        renderHighChart : function() {
             var height = share.getGraphHeight(tempOpt); 
             $('#'+mId+'_graph').height(height+'px').highcharts(highchartM.attributes);
        }

    });
	module.exports = ManualRenewView;
});

